// static/js/schedule_view.js

;(function () {
    // DOM 元素
    const dateInput = document.getElementById('view-date');
    const displayDate = document.getElementById('display-date');
    const prevBtn = document.getElementById('prev-day');
    const nextBtn = document.getElementById('next-day');
    const container = document.getElementById('cards-container');

    // 本地化格式化函数
    function formatLocal(date) {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        return `${y}年${m}月${d}日`;
    }

    // 统一加载卡片
    async function loadCards() {
        const dateStr = dateInput.value;
        container.innerHTML = '<p>加载中…</p>';
        try {
            const res = await fetch(`/api/schedules?date=${dateStr}`);
            if (!res.ok) throw new Error(`HTTP ${res.status}`);
            const list = await res.json();
            renderCards(list);
        } catch (e) {
            container.innerHTML = `<p class="text-danger">加载失败：${e.message}</p>`;
        }
    }

    window.loadCards = loadCards;

    // 渲染卡片
    function renderCards(list) {
        if (!list.length) {
            container.innerHTML = '<p class="text-muted">该日无排课</p>';
            return;
        }
        container.innerHTML = '';
        list.forEach(s => {
            const div = document.createElement('div');
            div.className = 'schedule-card';
            div.innerHTML = `
      <div class="card-row">
        <!-- 左侧时间列不变 -->
        <div class="time-col">
          <div class="start-time">${s.start_time}</div>
          <div class="mid-line">—</div>
          <div class="end-time">${s.end_time}</div>
        </div>
        <!-- 右侧 Grid -->
        <div class="details-grid">
          <!-- 行1 -->
          <div class="student">
            <i class="bi bi-person-fill me-1 text-primary"></i>
            <span>${s.student_name}</span>
          </div>
          <div class="grade">
            <i class="bi bi-easel-fill me-1 text-secondary"></i>
            <span>${s.grade}</span>
          </div>
          <div class="status">
            <button class="btn btn-sm btn-status ${s.status==='已上'?'btn-success':'btn-outline-primary'}"
                    data-id="${s.id}">
              <i class="bi ${s.status==='已上'?'bi-check-circle-fill':'bi-clock-fill'} me-1"></i>
              ${s.status}
            </button>
          </div>
          <!-- 行2：课程和跨两列的学校 -->
          <div class="course">
            <i class="bi bi-book-fill me-1 text-primary"></i>
            <span>${s.course}</span>
          </div>
          <div class="school">
            <i class="bi bi-building me-1 text-secondary"></i>
            <span>${s.school}</span>
          </div>
        </div>
      </div>
    `;
            container.appendChild(div);
        });

        // 为所有状态按钮绑定点击切换
        container.querySelectorAll('.btn-status').forEach(btn => {
            btn.addEventListener('click', async () => {
                const id = btn.getAttribute('data-id');
                try {
                    const res = await fetch(`/api/schedules/${id}/status`, {method: 'POST'});
                    if (!res.ok) throw new Error(`HTTP ${res.status}`);
                    const {status} = await res.json();
                    // 更新按钮样式和文本
                    btn.classList.toggle('btn-success', status === '已上');
                    btn.classList.toggle('btn-outline-primary', status !== '已上');
                    btn.innerHTML = `
          <i class="bi ${status === '已上' ? 'bi-check-circle-fill' : 'bi-clock-fill'} me-1"></i>
          ${status}
        `;
                } catch (e) {
                    console.error('切换状态失败', e);
                }
            });
        });
    }


    // 切换日期、刷新显示
    function loadForDate(dateStr) {
        dateInput.value = dateStr;
        const dt = new Date(dateStr);
        displayDate.textContent = formatLocal(dt);
        loadCards();
    }

    // 初始化今天
    const today = new Date();
    dateInput.value = today.toISOString().slice(0, 10);
    displayDate.textContent = formatLocal(today);

    // 事件绑定
    prevBtn.addEventListener('click', () => {
        const d = new Date(dateInput.value);
        d.setDate(d.getDate() - 1);
        loadForDate(d.toISOString().slice(0, 10));
    });

    nextBtn.addEventListener('click', () => {
        const d = new Date(dateInput.value);
        d.setDate(d.getDate() + 1);
        loadForDate(d.toISOString().slice(0, 10));
    });

    // 点击显示区触发原生日期选择
    displayDate.addEventListener('click', () => dateInput.click());

    // 原生选择器改变时同步
    dateInput.addEventListener('change', () => loadForDate(dateInput.value));

    // 首次加载
    document.addEventListener('DOMContentLoaded', loadCards);
})();
